package com.lzh.shijicloudstack.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.sql.*;

/**
 * @author luzhiheng
 * @date 2025-02-11
 */
@Component
public class JdbcUtil {

    @Value("${spring.datasource.url}")
    private String url;

    @Value("${spring.datasource.username}")
    private String username;

    @Value("${spring.datasource.password}")
    private String password;

    public int executeUpdateSql(String sql) {
        // 加载数据库驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return 0;
        }
        // 建立数据库连接
        try (Connection connection = DriverManager.getConnection(url, username, password)) {
            // 执行更新语句
            return executeUpdate(connection, sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    // 执行更新语句
    private int executeUpdate(Connection connection, String sql) throws SQLException {
        // 创建 Statement 对象
        try (Statement statement = connection.createStatement()) {
            // 执行更新语句，返回受影响的行数
            int rowsAffected = statement.executeUpdate(sql);
            return rowsAffected;
        }
    }

}
